//
//  NoticeListVC.swift
//  YueChat
//
//  Created by 1 on 2024/11/2.
//

import UIKit

class NoticeListVC: BaseVC {
    
    var conversations = [DMCCConversation]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.title = "通知消息"
        
        self.requestData()
        tableView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
    }
    
    @objc func requestData() {
        

        // 使用 dispatch_sync 来保证线程安全
        DispatchQueue.global().sync {
//            // 使用 _lock 来锁定临界区
            self.conversations = gosnConversation.getConversationList(.Service)//DMCCIMService.getInstance()!.getConversationWithLine([0, 1, 2], line: -1)
        }

//        self.conversations.forEach { con in
//            getServiceInfo(con: con)
//        }
        
        GK_main_async_safe {

            if self.conversations.isEmpty {
                self.view.insertSubview(self.nullView, aboveSubview: self.tableView)
            } else {
                self.nullView.removeFromSuperview()
            }
            self.tableView.reloadData()
        }
        
    }
    
    func getServiceInfo(con:DMCCConversation) {
//        let dapp = gosnDapp.getDappInfo(con.targetId)
        
        if gosnDapp.getDappInfo(con.targetId) == nil {
            Task {
                let res = await gosnDapp.fetchDappInfo(con.targetId)
                await MainActor.run {
                    if (res != nil){
//                        let user = DMCCUser()
                        
                    }
                }
                
            }
        }else{
            
        }
        
    }

    //MARK: Table
    // 表格视图节的数量
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    // 每个节的行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return conversations.count
    }

    // 表格视图单元格配置
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
        let info = conversations[indexPath.row]
        
        
        
//        let msg : DMCCMessage = (info.lastMessage != nil)  ?  info.lastMessage : DMCCMessage()
        
        if  info.timestamp > 0 {
            cell.timeLab.text = formatTimeLabel(info.timestamp)
        }
        
        cell.contentView.backgroundColor = info.isTop ? kGrayBG : .clear
        
//        if let msgText = info.lastMessage?.digest {
        if info.newestMessage.count > 0 {
            cell.contentLab.text = info.newestMessage
        }else{
            cell.contentLab.text = " "
        }

        if info.type == .Service {
            cell.icon.image = UIImage(named: "gonggaoIcon")
            cell.nickName.text = KLocalizedString("NotifyMessage")
        }
        
        if (info.isSilent) {
            cell.silentImg.isHidden = false;
//            cell.redImg.isHidden = !(info.unread > 0);
            cell.redImg.isHidden = true;
            cell.msgRead.isHidden = true
        } else {
            cell.silentImg.isHidden = true;
            cell.redImg.isHidden = true;
            if (info.unread > 0) {
                if (info.unread > 99) {
                    cell.msgRead.text = "99+";
                } else {
                    cell.msgRead.text = "\(info.unread)";
                }
                cell.msgRead.isHidden = false;
            } else {
                cell.msgRead.isHidden = true;
            }
        }
        
        if info.targetId.hasPrefix("OSNS") {
//                let dapp = gosnDapp.getDappInfo(info.targetId)
            if gosnDapp.getDappInfo(info.targetId) == nil {
                Task {
                    let res = await gosnDapp.fetchDappInfo(info.targetId)
                    await MainActor.run {
                        if (res != nil){
    //                        let user = DMCCUser()
                            cell.icon.sd_setImage(with: URL(string: res!.portrait), placeholderImage: kUserImage)
                            cell.nickName.text = res?.name
                        }
                    }
                    
                }
            }else{
                let dapp = gosnDapp.getDappInfo(info.targetId)
                cell.icon.sd_setImage(with: URL(string: dapp!.portrait), placeholderImage: kUserImage)
                cell.nickName.text = dapp?.name
            }
            
        }
        
        return cell
    }



    // 表格视图选择事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let info = conversations[indexPath.row]
        gosnConversation.clearUnread(info.targetId)
        navigationController?.pushViewController(ChatVC(conversation: info), animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }

    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
}
